package user_fav

import (
	"context"
	"go_final/mxshop_api/userop_web/api"
	"go_final/mxshop_api/userop_web/global"
	user_favpb "go_final/mxshop_api/userop_web/proto/protofile/user_fav"
	"net/http"
	"strconv"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	userID, _ := c.Get("userId")

	res, err := global.UserFavClient.GetFavList(context.Background(), &user_favpb.UserFavRequest{
		UserID: int32(userID.(uint)),
	})

	// TODO 通过商品服务湖区商品信息
	if err != nil {
		zap.S().Error("invoke GetFavList failed: ", err.Error())
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}

func Add(c *gin.Context) {
	goodsID := c.Param("id")
	goodsIDInt, _ := strconv.Atoi(goodsID)

	userID, _ := c.Get("userId")
	_, err := global.UserFavClient.AddUserFav(context.Background(), &user_favpb.UserFavRequest{
		UserID: int32(userID.(uint)),
		GoodID: int32(goodsIDInt),
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"msg": "收藏成功",
	})
}

func Delete(c *gin.Context) {
	goodsID := c.Param("id")
	goodsIDInt, _ := strconv.Atoi(goodsID)

	userID, _ := c.Get("userId")
	_, err := global.UserFavClient.DeleteUserFav(context.Background(), &user_favpb.UserFavRequest{
		UserID: int32(userID.(uint)),
		GoodID: int32(goodsIDInt),
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"msg": "取消收藏成功",
	})
}

func Detail(c *gin.Context) {
	goodsID := c.Param("id")
	goodsIDInt, _ := strconv.Atoi(goodsID)

	userID, _ := c.Get("userId")
	_, err := global.UserFavClient.GetUserFavDetail(context.Background(), &user_favpb.UserFavRequest{
		UserID: int32(userID.(uint)),
		GoodID: int32(goodsIDInt),
	})

	if err != nil {
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"msg": "记录存在",
	})
}
